package com.augurit.gzcgwsp.sendNotice.exchangedatatofx.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

import com.augurit.gzcgwsp.webservice.SFTPUtil;
import com.thoughtworks.xstream.XStream;

public class Object2XML {

	public void orderCancel(String acceptNo,ResourceBundle localResource,UnitValue unitValue,String businessCode) throws Exception {
		String spwj = localResource.getString("spwj");
		String spwjbackPath = localResource.getString("spwjbackPath");//xml存放路径
		Body body = new Body();
		ExchangeData exchangeData = new ExchangeData();
		Head head = new Head();
		Receivers receivers = new Receivers();
		RecordData recordData = new RecordData();
		UnitData unitData = new UnitData();
		UnitData2 unitData2 = new UnitData2();
		
		//设置ExchangeData
		exchangeData.setBody(body);
		exchangeData.setHead(head);		
		//设置receivers
		receivers.setReceiver("000001");
		//设置head
		head.setBusinessCode(businessCode);//设置head
		head.setSender("000003");
		head.setReceivers(receivers);
		head.setVersion("1");
		head.setPriority("1");
		//获取交换流水号
    	Date date2 = new Date();
		SimpleDateFormat myFmt = new SimpleDateFormat("yyMMddHHmmSS");
		String dateStr = myFmt.format(date2);
		String sn = "000003" + dateStr + acceptNo.substring(10);
		head.setSn(sn);
		//设置unitData2
		unitData2.setUnitIDName("approval_table");
		unitData2.setUnitValue(unitValue);
		//设置unitData
		unitData.setUnitIDName("accept_id");
		unitData.setUnitValue(acceptNo);//设置unitData
		//设置recordData
		recordData.setUnitData(unitData);
		recordData.setUnitData2(unitData2);
		//设置body
		body.setErrorMsg("错误信息定义，预留字段");
		body.setRecordData(recordData);       

        XStream xstream = new XStream();// 新建一个转换对象xstream
        String  xmlhead="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        // 设置别名 必须设置表明，否则显示的时候为类的全路径
        xstream.alias("exchange_data", ExchangeData.class);
        xstream.registerConverter(new NullConverter());  
        String xmlStr = xmlhead + xstream.toXML(exchangeData);
        xmlStr = changeEntityNameToApprovalData(xmlStr);
        String[] splitXmlStr = xmlStr.split("ApprovalData>");
        String splitXmlStrPart2 = changeStr(splitXmlStr[1]);
        String finalXml = splitXmlStr[0]+splitXmlStrPart2+splitXmlStr[2];
        System.out.println(finalXml);
        
        BufferedWriter out = null;
        BufferedWriter bout = null;
//        000003_04_[表名(事项名称,例如YW_RQ_QYZZ_INFO)]_[sn]_ 时间[yyyymmddHHMMSS].xml
        String fileName = spwj + "000003_" + head.getBusinessCode() + "_" + sn + "_" + dateStr + ".xml";
        String backUpfileName = spwjbackPath + "000003_" + head.getBusinessCode() + "_" + sn + "_" + dateStr + ".xml";
        try {
        	out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName), true), "utf-8"));
        	bout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(backUpfileName), true), "utf-8"));
        } catch (Exception e) {
         e.printStackTrace();
        }
        out.write(finalXml);
        out.flush();
        out.close();
        //备份
        bout.write(finalXml);
        bout.flush();
        bout.close();
        //上传到另外一台机器
//        SFTPUtil.uploadOtherFileForFx(fileName, fileName);
    }
	
	/**
	 * 把业务实体转成ApprovalData
	 * @param str
	 * @return
	 */
	public String changeEntityNameToApprovalData(String str){
		str = str.replace("UnitData2", "UnitData");
		str = str.replace("CsshljczForFx", "ApprovalData");
		str = str.replace("ShljYsForFx", "ApprovalData");
		str = str.replace("YwGgcsForFx", "ApprovalData");
		str = str.replace("YwHwShljqsForFx", "ApprovalData");
		str = str.replace("YwHwShSqbForFx", "ApprovalData");
		str = str.replace("YwRqQyjyxkForFx", "ApprovalData");
		str = str.replace("YwRqQyzzInfoForFx", "ApprovalData");
		str = str.replace("YwRqSsgdSqbForFx", "ApprovalData");
		str = str.replace("YwSrCsdlwjForFx", "ApprovalData");
		str = str.replace("YwSrDlzyForFx", "ApprovalData");
		str = str.replace("YwYnJzfqwczcJbxxForFx", "ApprovalData");
		str = str.replace("YwYnJzfqwczzPfsnForFx", "ApprovalData");
		str = str.replace("YwYnJzfqwczzXnForFx", "ApprovalData");
		str = str.replace("exchange__data", "exchange_data");
		return str;
	}
	
	/**
	 * 转换xml格式字符串
	 * @param xmlStr
	 * @return
	 */
	public String changeStr(String xmlStr){
		xmlStr = "<ApprovalData>"+xmlStr+"ApprovalData>";
//		System.out.println("xmlStr = "+xmlStr);
		xmlStr = processXmlElements(xmlStr);
		return xmlStr;
	}
	/**
	 * 把每个节点取出来出来
	 * @param xmlStr
	 * @return
	 */
	public String processXmlElements(String xmlStr) {
        //创建一个新的字符串
        StringReader read = new StringReader(xmlStr);
        //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
        InputSource source = new InputSource(read);
        //创建一个新的SAXBuilder
        SAXBuilder sb = new SAXBuilder();
        StringBuffer sbr = new StringBuffer();
        try {
            //通过输入源构造一个Document
            Document doc = sb.build(source);
            //取的根元素
            Element root = doc.getRootElement();
//            System.out.println(root.getName());//输出根元素的名称（测试）
            //得到根元素所有子元素的集合
            List jiedian = root.getChildren();
            String name = "";
            for(int j=0;j<jiedian.size();j++){
                Element xet = (Element) jiedian.get(j);
                name = formatStr(xet.getName());
                String value = xet.getValue();
                sbr.append("<"+name+">");
                sbr.append(value);
                sbr.append("</"+name+">\n");
            }
        } catch (JDOMException e) {
            // TODO 自动生成 catch 块
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 自动生成 catch 块
            e.printStackTrace();
        }
        return "ApprovalData>"+sbr.toString()+"</ApprovalData>";
    }
	
	/**
	 * 把acceptNo格式转换成accept_no
	 * @param str
	 * @return
	 */
	public String formatStr(String str){
		char ch = 'a';
		for(int i = 0;i<str.length();i++){
			ch = str.charAt(i);
			if(Character.isUpperCase(ch)){
				if(i == 0){//首字母把它变小写
					str = str.replace(String.valueOf(ch), String.valueOf(ch).toLowerCase());	
				}else{
					str = str.replace(String.valueOf(ch), "_"+String.valueOf(ch).toLowerCase());
				}							
			}
		}
		return str;
	}

    public static void main(String[] args) throws Exception {
    	Object2XML test = new Object2XML();
    	String acceptNo = "acceptNo";
    	System.out.println(test.formatStr(acceptNo));
                
    }
}
